package com.yssoft.service.supervise;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.yssoft.controller.supervise.ProductionInfo;
import com.yssoft.entity.inspection.TInspReport;
import com.yssoft.entity.inspection.TInspReportAtt;
import com.yssoft.entity.inspection.TInspReportDetail;
import com.yssoft.entity.production.TLabels;
import com.yssoft.entity.production.TPackageCode;
import com.yssoft.entity.supplier.CirculationInfo;
import com.yssoft.entity.supplier.InstockInfo;
import com.yssoft.entity.supplier.OutstockInfo;
import com.yssoft.entity.supplier.ProcurementInfo;
import com.yssoft.entity.supplier.ProductionBatch;
import com.yssoft.entity.supplier.ProductionBatchCustom;
import com.yssoft.entity.supplier.TEnterpriseCustom;
import com.yssoft.mapper.inspection.TInspReportAttMapper;
import com.yssoft.mapper.inspection.TInspReportDetailMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.mapper.production.TPackageCodeMapper;
import com.yssoft.mapper.supplier.ProductionBatchMapper;
import com.yssoft.mapper.supplier.TProductCountMapper;
import com.yssoft.mapper.supplier.TraceabilityQueryMapper;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.StringUtils;
import com.yssoft.utils.verificationCode.DateUtil;

@Service
public class TraceabilityQueryService {
	@Resource
	private TraceabilityQueryMapper traceabilityQueryMapper;
	@Autowired
	private TLabelsMapper labelsMapper;
	@Autowired
	private TPackageCodeMapper packageCodeMapper;
	@Resource
	private TInspReportAttMapper tInspReportAttMapper;
	@Resource
	private TInspReportDetailMapper tInspReportDetailMapper;

	/**
	 *
	    * @Title: queryProductByWorksheetId
	    * @Description: 单个商品信息
	    * @param @param custom
	    * @param @return    参数
	    * @return ProductCountCustom    返回类型
	    * @throws
	 */
	public Map<String, Object>  queryProductByWorksheetId(ProductionBatch custom) {
		//查询商品信息
		Map<String, Object>  param=new HashMap<>();
		param.put("worksheetId", custom.getWorksheetId());
		param.put("productId", custom.getProductId());
		Map<String, Object>   product=traceabilityQueryMapper.queryProductDetailByWorksheetId(param);
		if(product == null){
			return new HashMap<>();
		}
		param=new HashMap<>();
		//查询商品关联的图片信息
		param.put("productId", product.get("productId"));
		List<Map<String, Object> > productImgList=traceabilityQueryMapper.queryProductImgList(param);
		if(productImgList!=null &&  productImgList.size()>0) {
			product.put("imgList", productImgList);
			product.put("imgDefault", productImgList.get(0).get("pictureImg"));
		}else {
			product.put("imgList", "");
			product.put("imgDefault","");
		}
		if(product!=null && null!=product.get("worksheetDate") && null !=product.get("shelfLife")) {
			 int shelfLife=Integer.valueOf(product.get("shelfLife")+"");
			 //计算到期日子
			 Date date1= DateUtil.getAfterDays( product.get("worksheetDate")+""   , shelfLife);
			 //计算还剩多少天
			 int freeLife=DateUtil.differentDaysByMillisecond( new Date(),date1) ;
			 freeLife=freeLife<0?0:freeLife;
			 product.put("freeLife", freeLife);
			//计算百分比
			 Double rate =0d;
			 if(shelfLife!=0) {
				 rate=(double) ((freeLife/shelfLife )*100);
			 }
			 product.put("rate",rate);
		}


		return product;
	}
	/**
	 *
	    * @Title: queryEnterpriseById
	    * @Description: 查询企业简介
	    * @param @param custom
	    * @param @return    参数
	    * @return TEnterpriseCustom    返回类型
	    * @throws
	 */
	public TEnterpriseCustom queryEnterpriseById(ProductionBatch custom) {
		Map<String, Object>  param=new HashMap<>();
		param.put("enterpriseId", custom.getEnterpriseId());
		param.put("worksheetId", custom.getWorksheetId());
		TEnterpriseCustom enterprise=traceabilityQueryMapper.queryEnterpriseById(param);
		if(enterprise != null){
			if(enterprise.getContact() != null && enterprise.getContact().length() > 0){
				enterprise.setContact(  StringUtils.replaceWithStar( enterprise.getContact(), 2, enterprise.getContact().length())  );
			}
			if(enterprise.getPhone() != null && enterprise.getPhone().length() > 0){
				enterprise.setPhone(StringUtils.replaceWithStar( enterprise.getPhone(), 2, enterprise.getPhone().length())   );
			}
		}
		return enterprise;
	}
	/**
	 *
	    * @Title: queryProductionBatchByBatchId
	    * @Description: 查询批次信息
	    * @param @param custom
	    * @param @return    参数
	    * @return ProductionBatchCustom    返回类型
	    * @throws
	 */
	public ProductionBatchCustom queryProductionBatchByBatchId(ProductionBatch custom) {
		Map<String, Object>  param=new HashMap<>();
		param.put("worksheetId", custom.getWorksheetId());
		ProductionBatchCustom  batch=traceabilityQueryMapper.queryProductionBatchByBatchId(param);
		return batch;
	}
	/**
	 *
	    * @Title: queryProductionInfoList
	    * @Description: 查询产品生产信息
	    * @param @param custom
	    * @param @return    参数
	    * @return List<ProductionInfo>    返回类型
	    * @throws
	 */
	public List<ProductionInfo> queryProductionInfoList(ProductionBatch custom) {
		Map<String, Object>  param=new HashMap<>();
		param.put("worksheetId", custom.getWorksheetId());
		return traceabilityQueryMapper.queryProductionInfoList(param);
	}
	/**
	 *
	 * @param 根据企业id联动该企业下所有的产品
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 */
	public JSONObject queryAllProduct(String enterpriseId) throws IllegalAccessException, ClassNotFoundException {
		List<Map<String,Object>>  list=traceabilityQueryMapper.queryAllProduct(enterpriseId);
		return LayuiUtil.getJSONObjectByMap(list, 0, "", "");
	}
	/**
	 *
	    * @Title: queryAllBatch
	    * @Description: 根据产品id联动该产品下所有的批次
	    * @param @param productId
	    * @param @param code
	    * @param @return
	    * @param @throws IllegalAccessException
	    * @param @throws ClassNotFoundException    参数
	    * @return JSONObject    返回类型
	    * @throws
	 */
	public JSONObject queryAllBatch(String productId, String code) throws IllegalAccessException, ClassNotFoundException {
		List<Map<String,Object>>  list=traceabilityQueryMapper.queryAllBatch(productId,code);
		return LayuiUtil.getJSONObjectByObject(list, 0, "", "");
	}
	/**
	 *
	    * @Title: queryCirculationInfoList
	    * @Description: 根据加工单id流通信息查询
	    * @param @param custom
	    * @param @return    参数
	    * @return List<CirculationInfo>    返回类型
	    * @throws
	 */
	public List<CirculationInfo> queryCirculationInfoList(ProductionBatch custom) {
		return traceabilityQueryMapper.queryCirculationInfoList(custom);
	}
	/**
	 *
	    * @Title: queryProcurementInfoListByWorksheetId
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param custom
	    * @param @return    参数
	    * @return List<ProcurementInfo>    返回类型
	    * @throws
	 */
	public List<ProcurementInfo> queryProcurementInfoListByWorksheetId(ProductionBatch custom) {
		int worksheetId=custom.getWorksheetId();
		Integer productId=custom.getProductId();
		//如果商品ID为空，直接返回空列表（只显示当前商品的采购信息）
		if(productId==null) {
			return new ArrayList<>();
		}
		Map<String,Object> param=new HashMap<>();
		param.put("worksheetId", worksheetId);
		param.put("type", 1);//来源类型：1-物料 2-半成品
		param.put("productId", productId);//商品ID，用于过滤物料
		//根据加工单查询领料明细（只查询属于当前商品的物料）
		List<Map<String, Object>> collarMaterialDetailList=traceabilityQueryMapper.queryCollarMaterialDetailListByWorksheetId(param);
		//根据领料明细id-->入库申请单明细id
		param=new HashMap<>();
		param.put("worksheetId", worksheetId);
		param.put("p_type", 3);//来源类型：3采购
		List<Map<String, Object>> instockApplyDetailList=traceabilityQueryMapper.queryInstockApplyDetailListByCollarMaterialDetailId(param,collarMaterialDetailList);
		//根据入库申请查询采购信息
		param=new HashMap<>();
		param.put("source_type",2);//来源类型：3采购
		param.put("productId", productId);//商品ID，用于过滤物料
		List<ProcurementInfo>  list=traceabilityQueryMapper.queryProcurementInfoListByInstockApplyDetailList(param,instockApplyDetailList);
	//	List<ProcurementInfo>  list=traceabilityQueryMapper.queryProcurementInfoListByWorksheetId(worksheetId);
		//查询物料列表时，也过滤出只属于当前商品的物料
		param=new HashMap<>();
		param.put("productId", productId);
		List<Map<String,Object>>  materialList=traceabilityQueryMapper.selectMaterialListByWorksheetId(list,param);
		//过滤掉没有物料的采购信息，只返回有物料的采购信息
		List<ProcurementInfo> filteredList=new ArrayList<>();
		if(list!=null && list.size()>0) {
			for (ProcurementInfo procurementInfo:list) {
				List<Map<String,Object>> materiaDetaillList=new ArrayList<>();
				if(procurementInfo==null||procurementInfo.getRecipientId()==null) {
					continue;
				}
				int recipientId=procurementInfo.getRecipientId();
				for(Map<String,Object> map :materialList) {
					String _recipientId=map.get("recipientId")+"";
					if(_recipientId.equals( recipientId+""  )) {
						materiaDetaillList.add(map);
					}
				}
				procurementInfo.setMateriaDetaillList(materiaDetaillList);
				//只添加有物料的采购信息
				if(materiaDetaillList!=null && materiaDetaillList.size()>0) {
					filteredList.add(procurementInfo);
				}
			}
		}
		return filteredList;
	}
	/**
	 *
	    * @Title: collarMaterialRecordList
	    * @Description: 领料记录list
	    * @param @param worksheetId
	    * @param @return    参数
	    * @return List<Map<String,Object>>    返回类型
	    * @throws
	 */
	public List<Map<String, Object>> collarMaterialRecordList(String worksheetId) {
		// 领料主表信息
		List<Map<String, Object>>  mainList=traceabilityQueryMapper.collarMaterialList(worksheetId);
		// 领料详情信息
		List<Map<String, Object>>  detailList=traceabilityQueryMapper.collarMaterialdDetailList(worksheetId,mainList);
		if(mainList!=null&&mainList.size()>0) {
			for(Map<String, Object> main:mainList) {
				//收集明细
				List<Map<String, Object>>  m_detailList=new ArrayList<>();
				String m_collarId=main.get("collarId")+"";
				for(Map<String, Object> detail:detailList) {
					String collarId=detail.get("collarId")+"";
					if(m_collarId.equals( collarId )) {
						m_detailList.add(detail);
					}
				}
				main.put("detailList", m_detailList) ;
			}
		}
		return mainList;
	}
	public Map<String, Object>  queryWorksheetIdByLabelCode(String code) {
		Integer worksheetId = null;
		TLabels record = new TLabels();
		record.setCode(code);
		record.setDeleteFlag("0");
		TLabels lEntity = labelsMapper.selectOne(record);
		if(null == lEntity){
			return null;
		}
		if(lEntity.gettWorksheeId() == null && lEntity.gettPackageId() == null){
			return null;
		}

		if(lEntity.gettWorksheeId() != null){
			worksheetId=lEntity.gettWorksheeId();
		}else{
			TPackageCode pEntity = packageCodeMapper.selectByPrimaryKey(lEntity.gettPackageId());
			if(pEntity == null || pEntity.gettWorksheeId() == null){
				return null;
			}
			worksheetId=pEntity.gettWorksheeId();
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("labelId", lEntity.getId());
		map.put("worksheetId", worksheetId);
		return map;
	}
	/**
	 *
	    * @Title: queryInstockInfoList
	    * @Description: 根据标签id和加工单id查询入库信息
	    * @param @param map
	    * @param @return    参数
	    * @return List<InstockInfo>    返回类型
	    * @throws
	 */
	public InstockInfo queryInstockInfoList(Map<String, Object> map) {

		return traceabilityQueryMapper.queryInstockInfoList(map);
	}
	/**
	 *
	    * @Title: queryOutstockInfoList
	    * @Description: 根据标签id和加工单id查询出库信息
	    * @param @param map
	    * @param @return    参数
	    * @return List<OutstockInfo>    返回类型
	    * @throws
	 */
	public OutstockInfo queryOutstockInfoList(Map<String, Object> map) {
		return traceabilityQueryMapper.queryOutstockInfoList(map);
	}

	public Map<String, Object> queryiInspectionViewById(Integer tInspReportId) {
		Map<String, Object> report=new HashMap<>();
 		/*查询检验报告详细*/
		Map<String, Object> param = new HashMap<>();
		param.put("tInspReportId", tInspReportId);
		param.put("deleteFlag", "0");
		List<Map<String,Object>> detailList = tInspReportDetailMapper.queryInspReportDetail(param);
		report.put("tInspReportDetailList", detailList);
		/*查询检验报告附件*/
		TInspReportAtt tInspReportAtt = new TInspReportAtt();
		tInspReportAtt.settInspReportId(tInspReportId);
		tInspReportAtt.setDeleteFlag("0");
		List<TInspReportAtt> attList = tInspReportAttMapper.select(tInspReportAtt);
		report.put("tInspReportAttList", attList);
		return report;
	}
	public Map<String, Object> queryLabelByWorksheetId(ProductionBatch custom) {
		Map<String, Object> map=traceabilityQueryMapper.queryLabelByWorksheetId(custom);
		return map;
	}


}
